
import './storage.dart';
import 'dart:convert';
import '../config/config.dart';
class CartServices {

  
 
  //
  static addCart(item) async{
    item = CartServices.formCartData(item);
    try{
      List cartListData = json.decode(await Storage.getString('cartList'));
      // 判断购物车有没有当前数据
      bool hasData = cartListData.any((value){
         return value['_id'] == item['_id'] && value['selectAttr'] == item['selectAttr'];
      });
      if(hasData){
        cartListData = cartListData.map((value){
            if(value['_id'] == item['_id'] && value['selectAttr'] == item['selectAttr']){
                value['count'] = item['count'];  
            } 
            return value;
        });
      }else{
        cartListData.add(item);
      }
      await Storage.setString('cartList', json.encode(cartListData));
    }catch(e){
      List tempList = [];
      tempList.add(item);
      await Storage.setString('cartList', json.encode(tempList));
    }
  }

  //过滤数据
  static formCartData(item){
    final Map data = new Map<String,dynamic>();

    String sPic = Config.domain + item.pic.replaceAll('\\', '/');


    data['_id'] = item.sId;
    data['title'] = item.title;

    if(item.price is int || item.price is double){
       data['price'] = item.price;
    }else{
       data['price'] = double.parse(item.price);
    }
    data['selectAttr'] = item.selectAttr;
    data['count'] = item.count;
    data['pic'] = sPic;
    data['checked'] = true;
    return data;
  }
}